from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime, Boolean, Float, text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime

# 数据库连接配置 (这里先放占位符，后续会从 config 文件读取)
DATABASE_URL = ""

Base = declarative_base()

class LaixinRecord(Base):
    __tablename__ = "laixin"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    bh = Column(String(100), unique=True, index=True, nullable=False)
    txm = Column(String(100), nullable=True)
    start_time = Column(DateTime, default=datetime.now)
    status = Column(String(10), nullable=False) # 例如 "处理中", "成功", "失败"
    process_time = Column(Float, default=0.0) # 处理时间，单位秒
    case_instruction = Column(Text, nullable=True)
    response = Column(Text, nullable=True) # 存储JSON格式的响应
    error_info = Column(Text, nullable=True) # 存储错误信息
    is_delete = Column(Integer, default=0) # 0: 未删除, 1: 已删除

class NetRecord(Base):
    __tablename__ = "net"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    bh = Column(String(100), unique=True, index=True, nullable=False)
    ysbh = Column(String(100), nullable=True)
    start_time = Column(DateTime, default=datetime.now)
    status = Column(String(10), nullable=False) # 例如 "处理中", "成功", "失败"
    process_time = Column(Float, default=0.0) # 处理时间，单位秒
    fyrs = Column(Text, nullable=True) # 存储JSON格式的反映人信息
    cfj = Column(Text, nullable=True) # 存储JSON格式的重复件信息
    bfyrs = Column(Text, nullable=True) # 存储JSON格式的被反映人信息
    case_instruction = Column(Text, nullable=True)
    response = Column(Text, nullable=True) # 存储JSON格式的响应
    error_info = Column(Text, nullable=True) # 存储错误信息
    is_delete = Column(Integer, default=0) # 0: 未删除, 1: 已删除

# 初始化数据库引擎和会话
engine = None
SessionLocal = None

def init_db(database_url: str):
    """初始化数据库和存储适配器"""
    global engine, SessionLocal, DATABASE_URL
    DATABASE_URL = database_url
    
    # 初始化存储适配器
    from .storage_adapter import init_storage_adapter
    storage_adapter = init_storage_adapter(database_url)
    
    # 如果存储适配器使用MySQL，则初始化数据库连接
    if storage_adapter.is_using_mysql():
        try:
            # 增加连接超时时间，例如 30 秒
            engine = create_engine(DATABASE_URL, connect_args={"connect_timeout": 30})
            print(f"[DEBUG] 数据库引擎创建成功: {DATABASE_URL} (超时30s)")
        except Exception as e:
            print(f"[ERROR] 数据库引擎创建失败: {e}")
            raise
        
        try:
            SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
            print("[DEBUG] SessionLocal 创建成功。")
        except Exception as e:
            print(f"[ERROR] SessionLocal 创建失败: {e}")
            raise
        
        try:
            print("[DEBUG] 尝试创建/检查数据库表...")
            Base.metadata.create_all(bind=engine)
            print("[DEBUG] 数据库表创建/检查成功。")
        except Exception as e:
            print(f"[ERROR] 数据库表创建/检查失败: {e}")
            raise

        # 额外：为已有表补齐新增列（txm, ysbh）
        try:
            with engine.connect() as conn:
                # laixin.txm
                try:
                    rows = conn.execute(text("SHOW COLUMNS FROM laixin LIKE :col"), {"col": "txm"}).fetchall()
                    if not rows:
                        conn.execute(text("ALTER TABLE laixin ADD COLUMN txm VARCHAR(100) NULL"))
                        print("[DEBUG] 已为 laixin 表增加列 txm")
                except Exception as e:
                    print(f"[WARN] 检查/新增 laixin.txc 列时出错: {e}")

                # net.ysbh
                try:
                    rows = conn.execute(text("SHOW COLUMNS FROM net LIKE :col"), {"col": "ysbh"}).fetchall()
                    if not rows:
                        conn.execute(text("ALTER TABLE net ADD COLUMN ysbh VARCHAR(100) NULL"))
                        print("[DEBUG] 已为 net 表增加列 ysbh")
                except Exception as e:
                    print(f"[WARN] 检查/新增 net.ysbh 列时出错: {e}")
        except Exception as e:
            print(f"[WARN] 自动补齐新增列失败: {e}")
    else:
        print("[INFO] 使用内存存储，跳过数据库初始化")
        engine = None
        SessionLocal = None

def get_db():
    """获取数据库会话 - 兼容原有代码"""
    if SessionLocal:
        db = SessionLocal()
        try:
            yield db
        finally:
            db.close()
    else:
        # 如果没有数据库连接，返回None
        yield None


def get_storage_adapter():
    """获取存储适配器实例"""
    from .storage_adapter import get_storage_adapter as _get_storage_adapter
    return _get_storage_adapter() 